package com.dietdroid;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ResultListActivity extends ListActivity {

    ArrayList<FoodItem> results;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle b = getIntent().getExtras();
        FoodItemDataBase fdb = FoodItemDataBase.getInstance();
        results = fdb.searchFoodItems(b.getString("userInput"),
                b.getString("barcode"));

        ArrayList<String> names = new ArrayList<String>();
        if (!results.isEmpty()) {
            for (int x = 0; x < results.size(); x++) {
                names.add(results.get(x).getFood_name());
            }
            setListAdapter(new ArrayAdapter<String>(this, R.layout.iconrow,
                    R.id.foodname, names));
        } else {
            names.add("No Results Found");
            setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
        }
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        if (results != null && !results.isEmpty()) {
            Intent myIntent = new Intent(v.getContext(), FoodInfoActivity.class);

            Bundle b = new Bundle();
            b.putSerializable("food", results.get(position));
            myIntent.putExtras(b);

            startActivityForResult(myIntent, 0);
        } else {
            this.finish();
        }
    }
}